package com.learn.springcloud.zuulreverseproxytzuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Time : 2018/8/13 16:43
 * @Version : 1.0
 */
@Component
public class QueryParamRouteFilter extends ZuulFilter {

    private static List<String> userNames = Arrays.asList("aaa", "bbb", "ccc");

    @Override
    public String filterType() {
        return FilterConstants.ROUTE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        System.out.println("QueryParamRouteFilter...");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletResponse response = requestContext.getResponse();
        HttpServletRequest request = requestContext.getRequest();
        String flag = request.getParameter("flag");
        if ("aaa".equals(flag)) {
            // 不进行其他路由
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);

            // 返回错误信息
            try (ServletOutputStream outputStream = response.getOutputStream();) {
                outputStream.print("flag aaa error");
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if("bbb".equals(flag)){
            // 不进行其他路由
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);

            // 返回错误信息
            requestContext.setResponseBody("flag bbb error");
        }

        // 由于response 发生改变，所以需要设置回去
        requestContext.setResponse(response);
        return null;
    }
}
